package handler

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/share309/gojwt"
	"net/http"
	"shopcar/api/request"
	"shopcar/consts"
	"shopcar/internal/dao"
	"shopcar/internal/model"
	"time"
)

func Register(c *gin.Context) {
	var req request.UserRegister
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 10000,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{Mobile: req.Mobile}, &user)
	if user.Id != 0 {
		c.JSON(200, gin.H{
			"code": 10000,
			"msg":  "当前用户已存在",
			"data": nil,
		})
		return
	}
	result := dao.Create(&model.User{Mobile: req.Mobile, Password: req.Password})
	if !result {
		c.JSON(200, gin.H{
			"code": 10000,
			"msg":  "注册失败",
			"data": nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "注册成功",
		"data": nil,
	})

}

func Login(c *gin.Context) {
	var req request.UserLogin
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 10000,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{Mobile: req.Mobile}, &user)
	if user.Id == 0 {
		c.JSON(200, gin.H{
			"code": 10000,
			"msg":  "当前用户不存在",
			"data": nil,
		})
		return
	}
	if user.Password != req.Password {
		c.JSON(200, gin.H{
			"code": 10000,
			"msg":  "密码输入错误",
			"data": nil,
		})
		return
	}
	token, err := gojwt.NewJWT(consts.JWT_KEY).CreateToken(gojwt.CustomClaims{
		ID: user.Id,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 3600*24*7,
		},
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "生成token失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": token,
	})
}

func PerToken(c *gin.Context) {
	token, err := gojwt.NewJWT(consts.JWT_KEY).RefreshToken(c.Request.Header.Get("x-token"))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "生成token失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": token,
	})
}
